package main

import (
	"encoding/binary"
	"io"
)

const (
	MT_SUBMIT_JOB = 1 + iota //从server提交过来的任务
	MT_KILL_JOB
	MT_JOB_RESULT //任务执行完成的返回
	MT_QUERY_JOB
	MT_EXECUTOR_IDENT
	MT_STATUS_RESP
	MT_QUERY_RESP
	MT_SUBMIT_RESP
	MT_HEARTBEAT
	QUERY_EXTERNA_SHELL
	MT_EXIT       //程序退出消息
	MT_LOG_SUBMIT //实时提交日志信息

	MT_LOG_RESP   = 21 //日志确认消息
	STATUS_OK     = 1
	STATUS_FAIL   = 2
	STATUS_NO_JOB = 3
)

const PROTOCOL_VERSION = 1

//消息格式：4 byte(协议版本) + 4 byte(消息数据的长度) + 4 byte(消息的类型) + 消息数据
type MessageHeader struct {
	Version uint32
	Length  uint32
	Type    uint32
}

type Message struct {
	Type int
	Body interface{}
}

type ExecutorIdent struct {
	Id               string  `json:"id"`
	MaxConcurrentJob int     `json:"maxConcurrentJob"`
	IDC              string  `json:"IDC"`
	UUID             string  `json:"UUID"`
	JobID            string  `json:"jobID"`
	JobConf          JobConf `json:"jobConf"`
	SendIndex        int32   `json:"sendIndex"`
}

func (this *MessageHeader) Encode() []byte {
	//log.Debugf("encode header %+v", this)
	buf := make([]byte, 12)
	binary.BigEndian.PutUint32(buf, this.Version)
	binary.BigEndian.PutUint32(buf[4:8], this.Length)
	binary.BigEndian.PutUint32(buf[8:12], this.Type)
	return buf
}

func (this *MessageHeader) Decode(reader io.Reader) error {
	err := binary.Read(reader, binary.BigEndian, this)
	//log.Debugf("decode header %+v", this)
	return err
}
